<template>
	<!-- 商品详情页面 -->
	<view class="goods_detail_container">
		<!-- 轮播图 -->
		<view class="goods_slideshow">
			<swiper class="swiper" circular :indicator-dots="true" :autoplay="true" :interval="3000">
				<!-- 遍历展示轮播图 -->
				<swiper-item  v-for="(item, index) of goodsD.slideshows" :key="index">
					<view class="swiper-item">
						<image class="swiper_item_pic" :src="baseUrl + item.image_url" mode="widthFix"></image>
						<!-- <img class="swiper_item_pic" :src="baseUrl + item" alt="" /> -->
					</view>
				</swiper-item>
			</swiper>
		</view>
		<!-- 商品信息 -->
		<view class="goods_info">
			<view class="goods_info_name">
				{{ goodsD.goods_name }}
			</view>
			<view class="goods_info_price_lables">
				<view class="goods_info_price">
					￥<span style="font-size: 21px;">{{ goodsD.price }}</span>
				</view>
				<view class="goods_info_lables">
					<view class="goods_info_lable_item" v-for="(item, index) of goodsD.labels" :key="index">
						{{ item.label }}
					</view>
				</view>
			</view>
		</view>
		<!-- 店铺信息 -->
		<view class="store_info">
			<view class="store_info_left">
				<img class="store_pic" :src="storeD.store_picture ? (baseUrl + storeD.store_picture) : defaultImage" alt="" srcset="">
			</view>
			<view class="store_info_right">
				<view class="store_info_right_name">
					{{ storeD.store_name }}
				</view>
				<view class="store_info_right_start">
					<uni-rate v-model="storeD.start" :readonly="true" :size="16"/>
				</view>
			</view>
			<!-- 进店按钮 -->
			<view class="into_store">
				<button class="into_store_btn" type="default" @click="gotoPage('店铺')">进店</button>
			</view>
		</view>
		<!-- 商品详情图 -->
		<view class="goods_detial">
			<view class="goods_detial_title">商品详情</view>
			<view class="goods_detail_imgs" v-for="(item, index) of goodsD.detailImgs" :key="index">
				<image class="goods_detail_img" :src="baseUrl + item.image_url" alt="商品详情图" mode="widthFix"></image>
			</view>
		</view>
		
		<!-- 商品操作按钮 -->
		<view class="goods_bottom_ops">
			<!-- 店铺/收藏 -->
			<view class="goods_btns_left">
				<view 
					class="bottom_store_btn" 
					v-for="(item, index) of bottomBtnD" 
					:key="index"
					:class="{'startSty': index == 1}"
					@click="gotoPage(item.text)"
				>
					<view class="store_icon">
						<!-- 收藏按钮控制 -->
						<image v-if="index==1 && !isStart" 
							class="store_icon_img" 
							:src="'../../static/goodsDtail/' + item.icon" 
							alt="" 
							srcset="" 
							mode="widthFix"
							@click="updateStartState"
						/>
						<image v-if="index==1 && isStart" 
							class="store_icon_img" 
							src="../../static/goodsDtail/收藏ac.png" 
							alt="" 
							srcset="" 
							mode="widthFix"
							@click="updateStartState"
						/>
						<!-- 店铺 -->
						<image v-if="index==0" class="store_icon_img" :src="'../../static/goodsDtail/' + item.icon" alt="" srcset="" mode="widthFix"/>
					</view>
					<view class="store_text">
						{{ item.text }}
					</view>
				</view>
			</view>
			<!-- 加入购物车/立即购买 -->
			<view class="goods_btns_right">
				<view class="goods_btns_right_car right_btn" @click="openBottomPopup('car')">
					加入购物车
				</view>
				<view class="goods_btns_right_buy right_btn" @click="openBottomPopup('buy')">
					立即购买
				</view>
			</view>
		</view>
		<!-- 底部弹出框 -->
		<view class="bottom_popup">
			<uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0" background-color="#fff">
				<view class="popup_title">
					{{ popup_title }}
				</view>
				<!-- 立即购买视图，选择收货地址 组件 -->
				<view class="address_info" v-if="popup_title != '加入购物车'">
					<Address :noticeChoseAddress="noticeChoseAddress"></Address>
					<view class="colorBar"></view> 
				</view>
				
				<!-- 商品信息 -->
				<view class="popup_goods_info">
					<view class="popup_goods_info_pic">
						<image class="popup_goods_info_pic_img" :src="baseUrl + goodsD.cover" alt="" srcset="" mode="widthFix"/>
					</view>
					<view class="goods_info_popup">
						<view class="goods_info_popup_name">
							{{ goodsD.goods_name }}
						</view>
						<view class="goods_info_popup_price">
							￥<span style="font-size: 19px;">{{ goodsD.price }}</span>
						</view>
						<view class="goods_info_popup_number_select">
							<uni-number-box v-model="goods_select_number" />
						</view>
					</view>
				</view>
				<!-- 规格选择 -->
				<view class="popup_specification">
					<view class="popup_specification_item" v-for="(item, index) of goodsD.specificationsWithValues">
						<view class="specification_item_title">
							{{ item.speci_name }}
						</view>
						<view class="specification_item_selects" >
							<view class="specification_item_select" 
								v-for="(item1, index1) of item.specis" 
								:key="index1" 
								:class="{'specification_item_select_r': index1 != 0
								, 'selectedSpeci': specificationsCar[index].speciValue.specis_value == item1.specis_value}"
								@click="speciSelectHandle(index, item1.specis_value, item1.price)"
							>
								{{ item1.specis_value }}
							</view>
						</view>
					</view>
				</view>
				<!-- 加入购物车/立即购买按钮 -->
				<button 
					type="default" 
					class="addCarBtn"
					@click="carAndBugHandle"
				>
					{{popup_title }}
				</button>
			</uni-popup>
		</view>
	</view>
</template>

<script setup> 
import { ref, onMounted } from "vue";
import Address from "../../components/Address/Address.vue"

// 商品数据
let goodsD = ref({});
// 店铺数据
let storeD = ref({});
// 是否收藏
let isStart = ref(false);

// 商品选择数量
let goods_select_number = ref(1);
// 弹出框标题
let popup_title = ref("加入购物车");
// 是否选择了地址标识
let choseAddressFlag = ref(false);
// 收货地址信息
let addressInfo = ref({});

// 底部弹出框元素节点
let popup = ref(null);
// 弹出框内容类型，标识是购物车"car"还是立即购买"buy"
let popupType = ref("car");

// 购物车信息项集合
let specificationsCar = ref();

// 底部按钮数据
let bottomBtnD = ref([
	{
		icon: "店铺.png",
		text: "店铺"
	},
	{
		icon: "收藏.png",
		text: "收藏"
	},
])

// 图片基础路径
let baseUrl = uni.$baseUrl
let defaultImage = ''

onMounted(()=>{
	// 解析渲染商品数据
	parseGoodsInfo();
})

// 收货地址组件通知修改是否选择了收货地址
function noticeChoseAddress(isSelect){
	// console.log("接收到子组件中通知", isSelect);
	if(isSelect){
		choseAddressFlag.value = isSelect;
	}
}

// 弹出底部弹出框
function openBottomPopup(typeText){
	if(typeText == 'car'){
		popup_title.value = "加入购物车";
	}else{
		popup_title.value = "立即购买";
	}
	
	// 更改弹出框标识，并弹出信息框
	popupType.value = popupType;
	popup.value.open();
}

// 加入购物车或立即购买处理器
async function carAndBugHandle(){
	if(popup_title.value == "加入购物车"){
		// console.log("加入购物车触发", specificationsCar.value);
		// console.log(goodsD.value);
		// 构造商品信息和规格及数量信息加入本地存储中
		let carItem = {
			goodsInfo: goodsD.value,
			specifications: specificationsCar.value,
			number: goods_select_number.value,
			selected: false
		};
		// 存入LocalStore列表
		if(uni.getStorageSync("carList") == ""){
			let carList = [];
			carList.push(carItem)
			// 不存在任何购物车商品，直接存储
			uni.setStorageSync("carList", JSON.stringify(carList));
			// 成功提示，关闭弹出框
			uni.showToast({
				title: "加入购物车成功!",
				icon: "none"
			})
			popup.value.close();
			return 1;
		}
		let carListD = JSON.parse(uni.getStorageSync("carList"));
		// 判断商品是否已经在购物车之中
		
		for(let item of carListD){
			if(item.goodsInfo.goods_id == carItem.goodsInfo.goods_id){
				// 存在提示
				uni.showToast({
					title: '此商品已经存在您的购物车中',
					icon:"none"
				});
				return 1;
			}
		}
		carListD.push(carItem)
		// 添加到购物车，存储
		uni.setStorageSync("carList", JSON.stringify(carListD));
		uni.showToast({
			title: "加入购物车成功!",
			icon: "none"
		})
		popup.value.close();
	}else{ //立即购买逻辑，创建订单拉起支付
	
		// 检查是否选择了收货地址
		if(!choseAddressFlag.value){
			uni.showToast({
				title: '请选择收货地址',
				icon: "none"
			});
			return 1;
		}
		
		// 检查token状态
		let res = await uni.$checkToken();
		if(!res){return 0;}
		
		// 获取收货地址
		let addressE = JSON.stringify(uni.getStorageSync("address"));
		
		// 封装订单页面信息参数对象，跳转确定订单页面
		let orderInfo = {
			goodsInfo: goodsD.value,
			address: addressE,
			specifications: specificationsCar.value, // 选择的商品规格
			number: goods_select_number.value,
			selectedCoupon: false
		}
		
		uni.setStorageSync("orderInfo", JSON.stringify(orderInfo));
		
		uni.navigateTo({
			url:"/subPkg1/confirm_order/confirm_order"
		})
		
		return 1;
	}
}

// 规格项选择
function speciSelectHandle(selectSpeciIndex, specisValue, newPrice){
	// 根据传入的点击参数，动态渲染选择样式
	specificationsCar.value[selectSpeciIndex].speciValue.specis_value = specisValue;
	// 动态修改规格对应价格
	goodsD.value.price = newPrice;
}

// 从本地存储中取出用户点击的商品数据展示
function parseGoodsInfo(){
	goodsD.value = JSON.parse(uni.getStorageSync("goodsDetail"));
	// console.log(goodsD.value);
	// 检查商品收藏状态，并显示对应的图标
	checkGoodsStartState();
	// 根据商品所属店铺ID获取店铺信息
	getStoreInfo(goodsD.value.owner_store_id)
	// 解析并赋值购物车信息项列表
	parseCarSpeciItemList();
}

function parseCarSpeciItemList(){
	specificationsCar.value = [] // 初始化
	// 根据商品数据的规格项信息给specificationsCar初始化，用作加入购物车的数据和动态显示样式控制。
	for(let i = 0; i < goodsD.value.specificationsWithValues.length; i++){
		let speciTempObj = {
			speciName: goodsD.value.specificationsWithValues[i].speci_name, 
			speciValue: {...goodsD.value.specificationsWithValues[i].specis[0]}
		}
		specificationsCar.value.push(speciTempObj);
	}
	
	// console.log("默认添加的第一项规格：", specificationsCar.value);
	
}

// 获取店铺信息
async function getStoreInfo(storeId){
	// console.log("获取店铺信息...", storeId);
	const res = await uni.$http.get(`/store/getInfoById/${storeId}`);
	storeD.value = res.data.data;
}

// 查询商品的收藏状态
async function checkGoodsStartState(){
	// 获取请求参数：用户ID 和 商品ID
	let userInfo = uni.getStorageSync("userInfo");
	const res = await uni.$http.get(`/user/checkCollect/${userInfo.user_id}/${goodsD.value.goods_id}`);
	if(res.data.data){
		// 收藏了
		isStart.value = true;
	}else{
		// 没收藏
		isStart.value = false;
	}
	
	// console.log("检测用户收藏状态:", isStart.value);
}

// 更新收藏状态&显示图标
async function updateStartState(){
	// 检查token状态
	let res = await uni.$checkToken();
	if(!res){return 0;}
	
	uni.showLoading({
		title: "操作中..."
	})
	// 提交后端修改
	if(isStart.value){
		// 取消收藏逻辑
		execUpdateStart("disStart");
		return 1;
	}
	// 收藏逻辑
	execUpdateStart("start");
}

// 执行收藏更新
async function execUpdateStart(opsStr){
	let userInfo = uni.getStorageSync("userInfo");
	// 构造请求参数
	let paramObj = {
		userId: userInfo.user_id,
		goodsId: goodsD.value.goods_id,
		ops: opsStr
	}
	
	const res = await uni.$http.put("/goods/handleCollect", paramObj);
	
	// console.log(res);
	
	if(res.data.code == 0){
		uni.showToast({
			title: res.data.msg
		});
		return 0;
	}
	
	uni.hideLoading();
	if(opsStr == "start"){
		uni.$showT("收藏成功~")
	}else{
		uni.$showT("取消收藏成功~")
	}
	
	// 重新查询&渲染收藏状态
	checkGoodsStartState();
}

// 功能项点击
function gotoPage(text){
	if(text == "店铺"){
		// 取出店铺ID，传输到店铺页面查询店铺信息
		let storeId = storeD.value.store_id;
		uni.navigateTo({
			url:`/subPkg1/store/store?storeId=${storeId}`
		})
		return 1;
	}
}

</script>

<style lang="scss" scoped>
.swiper {
	height: 700rpx;
	position: relative;
}

.swiper_item_pic {
	width: 100%;
}

.goods_info{
	background-color: #fff;
	padding: 20rpx 20rpx;
}

.goods_info_price_lables{
	display: flex;
	margin-top: 25rpx;
}

.goods_info_price{
	color: red;
	font-weight: 600;
}

.goods_info_lables{
	display: flex;
	margin-left: 10rpx;
}

.goods_info_name{
	font-weight: 600;
}

.goods_info_lable_item{
	border: solid #ffb189 1px;
	padding: 0px 10rpx;
	margin-left: 15rpx;
	color: #ffb189;
	border-radius: 10rpx;
	font-size: 13px;
	display: flex;
	align-items: center;
}

.store_info{
	margin-top: 10rpx;
	background-color: #fff;
	display: flex;
	position: relative;
	padding: 20rpx 20rpx;
}

.store_info_left{
	width: 14%;
}

.store_info_right{
	width: 70%;
	// border: solid red 1px;
}

.store_pic{
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	border: solid #aaaaaa 1px;
}

.store_info_right_name{
	font-weight: 600;
}

.store_info_right_start{
	margin-top: 10rpx;
}

.into_store{
	position: absolute;
	right: 20rpx;
}

.into_store_btn{
	width: 120rpx;
	height: 60rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 15px;
	position: relative;
	top: 10rpx;
}

.goods_detial{
	// border: solid red 1px;
	margin-top: 10rpx;
	background-color: #fff;
	position: relative;
}

.goods_detail_img{
	width: 100%;
}

.goods_detial_title{
	padding: 20rpx 10rpx;
	font-size: 15px;
	color: #474747;
}

.goods_bottom_ops{
	background-color: #fff;
	position: fixed;
	bottom: 0px;
	height: 100rpx;
	width: 100vw;
	display: flex;
	justify-content: space-between;
}

.goods_btns_left{
	display: flex;
	font-size: 13px;
}

.bottom_store_btn{
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-content: center;
	margin-left: 20rpx;
}

.startSty{
	margin-left: 30rpx;
}

.goods_btns_right{
	display: flex;
	// border: solid red 1px;
	display: flex;
	justify-content: center;
	align-items: center;
	position: relative;
	right: 20rpx;
	height: 80%;
	margin: auto 0;
	font-size: 15px;
	border-radius: 15rpx;
	overflow: hidden;
}

.store_icon_img{
	width: 45rpx;
}

.store_text{
	text-align: center;
	font-size: 11px;
}

.right_btn{
	padding: 0px 20rpx;
}

.goods_btns_right_car{
	background-color: #ef9876;
	height: 100%;
	display: flex;
	align-items: center;
	color: #fff;
}

.goods_btns_right_buy{
	background-color: #f0bb3e;
	height: 100%;
	display: flex;
	align-items: center;
	color: #fff;
}

.popup_goods_info{
	display: flex;
	position: relative;
	margin-top: 15rpx;
}

.popup_goods_info_pic{
	width: 40%;
}

.goods_info_popup{
	width: 60%;
	margin-top: 20rpx;
}

.popup_goods_info_pic_img{
	width: 100%;
}

.popup_title{
	padding: 20rpx 25rpx;
	font-weight: 600;
	border-bottom: solid 1px #dedede;
}

.goods_info_popup_name{
	font-weight: 600;
	font-size: 15px;
}

.goods_info_popup_price{
	color: red;
	padding: 15rpx 0px;
	margin-top: 10rpx;
}

.goods_info_popup_number_select{
	width: 100%;
	margin-top: 15rpx;
	// border: solid red 1px;
	display: flex;
}

.popup_specification{
	border-top: solid #dedede 1px;
	padding: 15rpx 0px;
}

.specification_item_title{
	padding: 15rpx 10rpx;
	font-weight: 600;
	font-size: 15px;
}

.specification_item_selects{
	display: flex;
	flex-direction: row;
}

.specification_item_select{
	padding: 10rpx 15rpx;
	border: solid #bebebe 1px;
	border-radius: 15rpx;
	margin-left: 10rpx;
}

.specification_item_select_r{
	margin-left: 15rpx;
}

.addCarBtn{
	margin-top: 15rpx;
	color: white;
	background-color: #fb7811d9;
}

// 选择的规格项样式
.selectedSpeci{
	background-color: #ff9e2f;
	color: #fffdfd;
}

.colorBar{
	margin-top: 6rpx;
	height: 10rpx;
	background: linear-gradient(to right, #83d4ff, #ff5a5d, #83d4ff, #ff5a5d, #83d4ff, #ff5a5d, #83d4ff, #ff5a5d);
	border-radius: 20rpx;
}

</style>
